#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

import os
import re
import sys
import isbnlib
import mirrors.plugin


class Main:

    def __init__(self, sock):
        self.sock = sock
        self.dataDir = mirrors.plugin.params["storage-file"]["data-directory"]

    def run(self):
        fnList = os.listdir(self.dataDir)
        processed = 0
        progress = 0
        for fn in fnList:
            fullfn = os.path.join(self.dataDir, fn)
            if not os.path.isdir(fullfn):
                raise Exception("redundant file \"%s\"" % (fn))
            if not re.fullmatch("[0-9]+", fn) or isbnlib.notisbn(fn):
                raise Exception("invalid ISBN directory \"%s\"" % (fn))
            processed, progress = self._stepProgress(len(fnList), processed, progress)

    def _stepProgress(self, total, lastProcessed, lastProgress):
        newProcessed = lastProcessed + 1
        newProgress = newProcessed * 100 // total
        if newProgress > lastProgress:
            self.sock.progress_changed(newProgress)
        return (newProcessed, newProgress)


###############################################################################

if __name__ == "__main__":
    with mirrors.plugin.ApiClient() as sock:
        try:
            Main(sock).run()
            sock.progress_changed(100)
        except Exception:
            sock.error_occured(sys.exc_info())
            raise
